{% extends '_base_list.html' %}

{% block title %}
    资产管理
{% endblock %}


{% block top_css %}
    {{ super() }}
    <!--bees-->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bees.css') }}">
    <!-- zTree -->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='plugins/zTree/css/awesomeStyle/awesome.css') }}">
    <style>
        .treebox {
            position: relative;
        }

        .treebox #rMenu {
            position: absolute;
            left: 0;
            top: 0;
            cursor: pointer;
        }
    </style>
{% endblock %}


<!-- Content head -->
{% block head_title %}
    系统管理
{% endblock %}
{% block head_nav %}
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-home"></i></a></li>
        <li><a href="#">资产管理</a></li>
        <li class="active">资产信息</li>
    </ol>
{% endblock %}

{% block tip %}
    <div class="alert alert-info mar-no">
        <i class="fa fa-circle"></i>&nbsp;&nbsp;左侧是资产树，右击可以新建、删除、更改树节点，授权资产也是以节点方式组织的，右侧是属于该节点下的资产。
    </div>
{% endblock %}

<!-- Content body -->
{% block title_filter %}
    <div class="filter">
        <div class="row">
            <div class="col-xs-12 col-sm-2">
                <div class="form-group">
                    <input type="text" class="form-control" name="create_time" placeholder="请选择日期日期" autocomplete="off">
                </div>
            </div>

            <div class="col-xs-12 col-sm-3 pull-right">
                <div class="form-group">
                    <div class="input-group">
                        <input type="text" name="search" placeholder="请输入资产的主机名" class="form-control">
                        <span class="input-group-btn">
                            <button name="search" class="btn btn-mint" type="button">
                                <i class="fa fa-search"></i>
                            </button>
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block body_operator %}
    <div class="operator mar-btm">
        <div class="row">
            <div class="col-xs-12 text-center">
                {% if current_user.has_perm('assets-asset-create') %}
                    <button class="btn btn-primary btn-sm" id="add"><i class=""></i> 新增资产</button>
                {% endif %}
                {% if current_user.has_perm('assets-asset-update') %}
                    <button class="btn btn-mint btn-sm" id="edit"><i class=""></i> 修改资产</button>
                {% endif %}
                {% if current_user.has_perm('assets-asset-delete') %}
                    <button class="btn btn-danger btn-sm" id="del"><i class=""></i> 删除资产</button>
                {% endif %}
                {% if current_user.has_perm('assets-asset-connectivity') %}
                    <button class="btn btn-purple btn-sm" id="hardware"><i class=""></i> 更新硬件信息</button>
                {% endif %}
                {% if current_user.has_perm('assets-asset-hardware') %}
                    <button class="btn btn-info btn-sm" id="connectivity"><i class=""></i> 测试可连接性</button>
                {% endif %}
            </div>
        </div>
    </div>
{% endblock %}

{% block body_table %}

    <div class="row">
        <div class="col-xs-12 col-sm-2">
            <div class="treebox">
                <div id="nTree" class="ztree">
                </div>
                <div id="rMenu">
                    <ul class="dropdown-menu menu-actions">
                        <li id="m_create" tabindex="-1" onclick="addTreeNode();"><a><i class="fa fa-plus-square-o"></i> 新建节点 </a></li>
                        <li id="m_update" tabindex="-1" onclick="editTreeNode();"><a><i class="fa fa-pencil-square-o"></i> 重命名节点 </a></li>
                        <li id="m_delete" tabindex="-1" onclick="removeTreeNode();"><a><i class="fa fa-minus-square"></i> 删除节点 </a></li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="col-xs-12 col-sm-10">
            <table id="assetTable" class="table table-auto"></table>
        </div>
    </div>

{% endblock %}


{% block buttom_js %}
    {{ super() }}
    <!--bees-->
    <script src="{{ url_for('static', filename='js/bees.js') }}"></script>
    <!--zTree-->
    <script src="{{ url_for('static', filename='plugins/zTree/js/jquery.ztree.all.js') }}"></script>

    <script>
        var zTree, rMenu, node_id = null;
        var showMenu = false;

        function initAssetTable() {
            bees.initDaterangepicker($('input[name="create_time"]'),{
                opens: "right",
                timePicker: false,
                timePickerSeconds: false,
                singleDatePicker: false,
                locale: {
                    format: 'YYYY-MM-DD'
                }
            });

            // 回填和初始化默认过滤参数
            var createTimeEle = $("input[name='create_time']");
            var searchEle = $('input[name="search"]');

            var filterParams = JSON.parse(window.sessionStorage.getItem("filterParams"));
            if(filterParams){
                // 回填表单过滤条件
                createTimeEle.val(filterParams.create_time);
                searchEle.val(filterParams.search);
                window.sessionStorage.removeItem("filterParams");
            }else {
                // 默认表单过滤条件
                filterParams = {
                    'create_time': createTimeEle.val(),
                    'search': searchEle.val(),
                    'node': node_id
                };
            }
            $.fn.beesTable.defaultFilterParams(filterParams);

            // 初始化表格
            var $tableEle = $("#assetTable");
            var options = {
                columns: [
                    {title: '选择', field: 'selected', radio: true},
                    {title: '主机名称', field: 'hostname', sortable: false},
                    {title: 'IP地址', field: 'manage_ip', sortable: false},
                    {title: '管理用户', field: 'admin_user', sortable: false},
                    {title: '硬件信息', field: 'hardware_info', sortable: false},
                    {title: '可连接', field: 'connectivity', sortable: false,
                        formatter: function (value, row, index, field) {
                            if(value === 'Unreachable'){
                                return '<i class="fa fa-circle text-info"></i>'
                            }else if(value === 'Reachable'){
                                return '<i class="fa fa-circle text-success"></i>'
                            }else if(value === 'Unknown'){
                                return '<i class="fa fa-circle text-danger"></i>'
                            }
                        }
                    },
                    {title: '创建时间', field: 'create_time', sortable: true}
                ],
                url:'{{ url_for("assets.api-asset-list") }}',
                sortName: 'create_time',
                sortOrder: 'desc'
            };
            var table = $tableEle.beesTable(options);

            // 搜索
            bees.bindTableSearch({
                table: $tableEle,
                searches: [
                    {eventType:'change', eventSource:createTimeEle, data:function () {
                            return {'create_time': createTimeEle.val()};
                        }
                    },
                    {eventType:'click', eventSource:$('button[name="search"]'), data: function () {
                            return {'search': searchEle.val()}
                        }
                    }
                ]
            });

            // 操作
            bees.bindTableOperator({
                table: $tableEle,
                operator: {
                    add: {
                        href: '{{ url_for('assets.asset-create') }}'
                    },
                    show: {
                        disable: true
                    },
                    edit: {
                        href: '{{ url_for('assets.asset-update', pk=default_pk) }}'
                    },
                    del: {
                        confirmCallback: function (data) {
                            setAjaxCSRFToken();
                            $.ajax({
                                type: 'post',
                                url: '{{ url_for("assets.asset-delete", pk=default_pk) }}'.replace(bees.defaultPK, data.id),
                                data : {},
                                success: function (result) {
                                    if (result.code != 200) {
                                        bees.tipError({
                                            message: result.data.message
                                        });
                                    }else {
                                       bees.tipSuccess({
                                            message: "删除成功"
                                        });
                                    }

                                    //reload
                                    table.bt.bootstrapTable('refresh');
                                }
                            })
                        }
                    }
                }
            });

            $("#connectivity").on('click', function () {
                // 获取选择的数据
                var rows = $tableEle.bootstrapTable('getSelections');
                var data = rows[0];
                var count = rows.length;
                // 没有选择对应的行
                if(!count){
                    bees.tipWaring({
                        message: '请选择需要操作的行'
                    });
                }else {
                    setAjaxCSRFToken();
                    $.ajax({
                        type: 'post',
                        url: '{{ url_for("assets.asset-connectivity", pk=default_pk) }}'.replace(bees.defaultPK, data.id),
                        data : {},
                        success: function (result) {
                            if (result.code != 200) {
                                bees.tipError({
                                    message: result.data.message
                                });
                            }else {
                                var task_id = result.data.task_id;
                                var url = '{{ url_for("ops.celery-task-log", pk=default_pk) }}'.replace(bees.defaultPK, task_id);
                                window.open(url, '', 'width=800,height=600,left=300,top=160')
                            }

                            //reload
                            //table.bt.bootstrapTable('refresh');
                        }
                    })
                }
            });

            $("#hardware").on('click', function () {
                // 获取选择的数据
                var rows = $tableEle.bootstrapTable('getSelections');
                var data = rows[0];
                var count = rows.length;
                // 没有选择对应的行
                if(!count){
                    bees.tipWaring({
                        message: '请选择需要操作的行'
                    });
                }else {
                    setAjaxCSRFToken();
                    $.ajax({
                        type: 'post',
                        url: '{{ url_for("assets.asset-hardware", pk=default_pk) }}'.replace(bees.defaultPK, data.id),
                        data : {},
                        success: function (result) {
                            if (result.code != 200) {
                                bees.tipError({
                                    message: result.data.message
                                });
                            }else {
                                var task_id = result.data.task_id;
                                var url = '{{ url_for("ops.celery-task-log", pk=default_pk) }}'.replace(bees.defaultPK, task_id);
                                window.open(url, '', 'width=800,height=600,left=300,top=160')
                            }

                            //reload
                            //table.bt.bootstrapTable('refresh');
                        }
                    })
                }
            })
        }

        function initNodeTree(options) {
            var treeUrl = '{{ url_for('assets.api-node-tree') }}?type=1';
            var setting = {
                view: {
                    dblClickExpand: false,
                    showLine: true
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                async: {
                    enable: true,
                    url: treeUrl,
                    autoParam: ["id=key", "name=n", "level=lv"],
                    type: 'get'
                },
                edit: {
                    enable: true,
                    showRemoveBtn: false,
                    showRenameBtn: false,
                    drag: {
                        isCopy: true,
                        isMove: true
                    }
                },
                callback: {
                    onRightClick: onRightClick,
                    beforeClick: beforeClick,
                    onRename: onRename,
                    onSelected: onSelected,
                    beforeDrag: beforeDrag,
                    onDrag: onDrag,
                    beforeDrop: beforeDrop,
                    onDrop: onDrop,
                    beforeAsync: defaultCallback("Before async")
                }
            };

            $.get(treeUrl, function (data, status) {
                zTree = $.fn.zTree.init($("#nTree"), setting, data);
                if (options.showMenu) {
                    showMenu = true;
                    rMenu = $("#rMenu");
                }
            });
        }

        function onBodyMouseDown(event){
            if (!(event.target.id === "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                rMenu.css({"visibility" : "hidden"});
            }
        }

        function showRMenu(type, x, y) {
            var offset = $("#nTree").offset();
            var scrollTop = document.querySelector('.treebox').scrollTop;
            x -= offset.left;
            y -= offset.top + scrollTop;
            x += document.body.scrollLeft;
            y += document.body.scrollTop + document.documentElement.scrollTop;
            rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
            $("#rMenu ul").show();
            $("body").bind("mousedown", onBodyMouseDown);
        }

        function hideRMenu() {
            if (rMenu) rMenu.css({"visibility": "hidden"});
            $("body").unbind("mousedown", onBodyMouseDown);
        }

        function onRightClick(event, treeId, treeNode) {
            if (!showMenu) {
                return
            }
            if (!treeNode && event.target.tagName.toLowerCase() !== "button" && $(event.target).parents("a").length === 0) {
                zTree.cancelSelectedNode();
                showRMenu("root", event.clientX, event.clientY);
            } else if (treeNode && !treeNode.noR) {
                zTree.selectNode(treeNode);
                showRMenu("node", event.clientX, event.clientY);
            }
        }

        function addTreeNode() {
            hideRMenu();
            var parentNode = zTree.getSelectedNodes()[0];
            if (!parentNode){
                return
            }
            zTree.expandNode(parentNode, true, null, null); // 打开节点

            var url = "{{ url_for('assets.api-node-add-children', pk=default_pk) }}".replace(bees.defaultPK, parentNode.meta.node.id);
            setAjaxCSRFToken();
            $.post(url, {}, function (results){
                if (results.code === 200) {
                    var newNode = {
                        id: results.data.meta.node["key"],
                        name: results.data.meta.node["value"],
                        pId: parentNode.id,
                        meta: {
                            "node": results.data.meta.node
                        }
                    };
                    newNode.checked = zTree.getSelectedNodes()[0].checked;

                    zTree.addNodes(parentNode, 0, newNode); // 新增节点
                    var node = zTree.getNodeByParam('id', newNode.id, parentNode);
                    zTree.editName(node);

                    bees.tipSuccess({
                        message: '节点创建成功'
                    });
                } else {
                    bees.tipError({
                        message: '节点创建失败'
                    });
                }
            });
        }

        function removeTreeNode() {
            hideRMenu();
            var current_node = zTree.getSelectedNodes()[0];
            if (!current_node){
                return
            }
            var current_node_id = current_node.meta.node.id;
            var url = "{{ url_for('assets.api-node-delete', pk=default_pk) }}".replace(bees.defaultPK, current_node_id);

            setAjaxCSRFToken();
            $.post(url, {}, function (results){
                if (results.code === 200) {
                    zTree.removeNode(current_node);
                    bees.tipSuccess({
                        message: '删除节点成功'
                    });
                } else if(results.code === 400){
                    bees.tipError({
                        message: results.data.message
                    });
                }else {
                    bees.tipError({
                        message: '删除节点失败'
                    });
                }
            });
        }

        function editTreeNode() {
            hideRMenu();
            var current_node = zTree.getSelectedNodes()[0];
            if (!current_node){
                return
            }
            current_node.name = current_node.meta.node.value;
            zTree.editName(current_node);
        }

        function onRename(event, treeId, treeNode, isCancel) {
            var current_node_id = treeNode.meta.node.id;
            var url = "{{ url_for('assets.api-node-rename', pk=default_pk) }}".replace(bees.defaultPK, current_node_id);
            var data = {"value": treeNode.name};
            if (isCancel){
                return
            }

            setAjaxCSRFToken();
            $.post(url, data, function (results){
                if (results.code === 200) {
                    var assets_amount = treeNode.meta.node.assets_amount;
                    if (!assets_amount) {
                        assets_amount = 0;
                    }
                    treeNode.name = treeNode.name + ' (' + assets_amount + ')';
                    zTree.updateNode(treeNode);

                    bees.tipSuccess({
                        message: '重命名节点成功'
                    });
                } else {
                    bees.tipError({
                        message: '重命名节点失败'
                    });
                }
            });
        }

        function beforeDrop(treeId, treeNodes, targetNode, moveType) {
            var treeNodesNames = [];
            $.each(treeNodes, function (index, value) {
                treeNodesNames.push(value.name);
            });

            var msg = "你想移动节点: `" + treeNodesNames.join(",") + "` 到 `" + targetNode.name + "` 下吗?";
            return confirm(msg);
        }

        function onDrop(event, treeId, treeNodes, targetNode, moveType) {
            var treeNodesIds = [];
            $.each(treeNodes, function (index, value) {
                treeNodesIds.push(value.meta.node.id);
            });
            var url = "{{ url_for('assets.api-node-move-children', pk=default_pk) }}".replace(bees.defaultPK, targetNode.meta.node.id);
            var data = {nodes: JSON.stringify(treeNodesIds)};

            setAjaxCSRFToken();
            $.post(url, data, function (results){
                if (results.code === 200) {
                    bees.tipSuccess({
                        message: '移动节点成功'
                    });
                } else {
                    bees.tipError({
                        message: '移动节点失败'
                    });
                }
            });
        }

        function onSelected(event, treeNode) {
            node_id = treeNode.meta.node.id;
            zTree.expandNode(treeNode, true);
            $("#assetTable").beesTable("search", {'node': node_id});
        }

        function beforeClick() {
            return true;
        }

        function beforeDrag() {
            return true
        }

        function onDrag() {

        }

        function defaultCallback(action) {
            function logging() {
                console.log(action)
            }
            return logging
        }

        $(function () {
            initAssetTable();

            initNodeTree({
                showMenu: true
            });
        });

    </script>

{% endblock %}
